#include <p24FJ256GA106.h>
#include <stdio.h>

/*
 * Koppeltabel:
 * SW    | R      | CN
 * 1     | E7     | 65
 * 2     | E6     | 64
 * 3     | F0     | 68
 * 4     | F1     | 69
 * 5     | E2     | 60
 * 6     | E3     | 61
 * 7     | E4     | 62
 * 8     | E5     | 63
 */

// TRIS
#define SW1_TRIS 			TRISEbits.TRISE7 
#define SW2_TRIS 			TRISEbits.TRISE6 
#define SW3_TRIS 			TRISFbits.TRISF0 
#define SW4_TRIS 			TRISFbits.TRISF1 
#define SW5_TRIS 			TRISEbits.TRISE2 
#define SW6_TRIS 			TRISEbits.TRISE3 
#define SW7_TRIS 			TRISEbits.TRISE4 
#define SW8_TRIS 			TRISEbits.TRISE5 
// Programmeer pin
#define PR_MODE_TRIS 			TRISBbits.TRISB8 

// PORT
#define SW1					PORTEbits.RE7
#define SW2					PORTEbits.RE6
#define SW3					PORTFbits.RF0
#define SW4					PORTFbits.RF1
#define SW5					PORTEbits.RE2
#define SW6					PORTEbits.RE3
#define SW7					PORTEbits.RE4
#define SW8					PORTEbits.RE5

#define PR_MODE				PORTBbits.RB8

void InitSwitches(void)
{

  // Make inputs
  SW1_TRIS	= 1; 
  SW2_TRIS	= 1; 
  SW3_TRIS	= 1; 
  SW4_TRIS	= 1; 
  SW5_TRIS	= 1; 
  SW6_TRIS	= 1; 
  SW7_TRIS	= 1; 
  SW8_TRIS	= 1; 

  PR_MODE_TRIS	= 1;

  // enable input change notification
  CNEN5bits.CN65IE = 1; 
  CNEN5bits.CN64IE = 1; 
  CNEN5bits.CN68IE = 1; 
  CNEN5bits.CN69IE = 1; 
  CNEN4bits.CN60IE = 1; 
  CNEN4bits.CN61IE = 1; 
  CNEN4bits.CN62IE = 1; 
  CNEN4bits.CN63IE = 1; 

  CNEN2bits.CN26IE = 1;  //PR_MODE
  
  //CNEN4bits.CN63IE = 1; 

  // Enable Pull-up resistor
  CNPU5bits.CN65PUE = 1;
  CNPU5bits.CN64PUE = 1;
  CNPU5bits.CN68PUE = 1;
  CNPU5bits.CN69PUE = 1;
  CNPU4bits.CN60PUE = 1;
  CNPU4bits.CN61PUE = 1;
  CNPU4bits.CN62PUE = 1;
  CNPU4bits.CN63PUE = 1;  


  // priority onderzoekn IPC4bits.CNIP = 7;		// set IP as 7
  IFS1bits.CNIF = 0; 		// clear the interrupt flag
  IEC1bits.CNIE = 1;		// enable the interrupt on change notification

}

unsigned int GetIOWord(void)
{
  unsigned int TotalSW;
  TotalSW =  SW1;
  TotalSW |= (SW2 << 1);
  TotalSW |= (SW3 << 2);
  TotalSW |= (SW4 << 3);
  TotalSW |= (SW5 << 4);
  TotalSW |= (SW6 << 5);
  TotalSW |= (SW7 << 6);
  TotalSW |= (SW8 << 7);

  return TotalSW;
}

void SW2SR(void)
{
  WriteSR(GetIOWord());
}

// change notification interrupt service routine
void _ISR _CNInterrupt(void) 
{
  // Programmeer bordje aangesloten?
  if(PR_MODE==1) 
  {
	// Stop met pwm uitzenden, straks via programmeer mode kunnen de kleppen ook aangestuurd worden.
	PWM_SB_Clear();
  } 
  else 
  {
	ClearVarsPR_Mode();
  } 

  SW2SR();
  IFS1bits.CNIF = 0; 		// clear the interrupt flag
}